<template>
    <!--TODO 目前先完成明细，概览也再议-->
    <div>
        <el-tabs
            v-model="activateName"
            type="card"
            @click="handleClick"
        >
            <el-tab-pane
                label="概览"
                name="overview"
            >
                <el-row>
                    <el-col
                        :span="4"
                        :offset="2"
                    >
                        <el-row>
                            <el-col :span="10">
                                <img
                                    src="/images/icon-title-01.png"
                                    style="float: right"
                                />
                            </el-col>
                            <el-col :span="14">
                                <div style="text-align: center;">
                                    <span>匹配成功率</span>
                                </div>
                                <div class="div-class">
                                    <span class="span-class">
                                        {{ (biopsyStatusData.matchedRate * 100).toFixed(1) }}%
                                    </span>
                                </div>
                            </el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="4">
                        <el-col :span="10">
                            <img
                                src="/images/icon-title-02.png"
                                style="float: right"
                            />
                        </el-col>
                        <el-col :span="14">
                            <div style="text-align: center">
                                <span>平均切片数</span>
                            </div>
                            <div class="div-class">
                                <!--<span class="span-class">{{1}}</span>-->
                                <span class="span-class">{{ biopsyStatusData.averageBiopsy }}</span>
                            </div>
                        </el-col>
                    </el-col>
                    <el-col :span="4">
                        <el-col :span="10">
                            <img
                                src="/images/icon-title-03.png"
                                style="float: right"
                            />
                        </el-col>
                        <el-col :span="14">
                            <div style="text-align: center">
                                <span>切片总量</span>
                            </div>
                            <div class="div-class">
                                <span class="span-class">
                                    {{ formatBytes(biopsyStatusData.biopsyStorageCount) }}
                                </span>
                            </div>
                        </el-col>
                    </el-col>
                    <el-col :span="4">
                        <el-col :span="10">
                            <img
                                src="/images/icon-title-04.png"
                                style="float: right"
                            />
                        </el-col>
                        <el-col :span="14">
                            <div style="text-align: center">
                                <span>最大切片</span>
                            </div>
                            <div class="div-class">
                                <span class="span-class">
                                    {{ formatBytes(biopsyStatusData.maxBiopsy) }}
                                </span>
                            </div>
                        </el-col>
                    </el-col>
                    <el-col :span="4">
                        <el-col :span="10">
                            <img
                                src="/images/icon-title-05.png"
                                style="float: right"
                            />
                        </el-col>
                        <el-col :span="14">
                            <div style="text-align: center">
                                <span>最小切片</span>
                            </div>
                            <div class="div-class">
                                <span class="span-class">
                                    {{ formatBytes(biopsyStatusData.minBiopsy) }}
                                </span>
                            </div>
                        </el-col>
                    </el-col>
                </el-row>
                <el-row style="margin-top: 20px">
                    <el-col :span="24">
                        <div
                            id="consultationBar"
                            style="width: 1080px; height: 400px;"
                        >
                        </div>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <div
                            id="consultationLine"
                            style="width: 1080px; height: 400px"
                        >
                        </div>
                    </el-col>
                </el-row>
            </el-tab-pane>

            <el-tab-pane
                label="明细"
                name="detail"
            >
                <el-row style="margin-top: 10px;">
                    <base-table
                        ref="biopsyHistoryTable"
                        class="data-table-style"
                        :data="biopsyHistoryTable.data"
                        :header="biopsyHistoryTable.header"
                        :operation="biopsyHistoryTable.operation"
                        :pageInfo="biopsyHistoryTable.pageInfo"
                        @handleClick="biopsyHistoryTableButtonClick"
                        @pageJumpTo="biopsyHistoryTablePageJumpTo"
                        @sizeChange="biopsyHistoryTableSizeChange"
                    >
                    </base-table>
                </el-row>
            </el-tab-pane>
        </el-tabs>
        <el-dialog
            :close-on-click-modal="false"
            title="扫描批次归档详情"
            :visible.sync="biopsyHistoryDialog.visible"
            width="60%"
        >

            <el-row class="line-text">
                <el-col :span="8">
                    <span class="content-text">扫描批次序号: {{ biopsyHistory.id }}</span>
                </el-col>
                <el-col :span="8">
                    <span class="content-text">操作员: {{ biopsyHistory.userName }}</span>
                </el-col>
                <el-col :span="8">
                    <span class="content-text">扫描状态：{{ biopsyHistory.status }}</span>
                </el-col>
            </el-row>
            <el-row class="line-text">
                <el-col :span="8">
                    <span class="content-text">扫描总量: {{ biopsyHistory.scanFileCount }}</span>
                </el-col>
                <el-col :span="8">
                    <span class="content-text">自动匹配数量: {{ biopsyHistory.autoMatchCount }}</span>
                </el-col>
                <el-col :span="8">
                    <span class="content-text">手动匹配数量：{{ biopsyHistory.manualMatchCount }}</span>
                </el-col>
            </el-row>
            <el-row class="line-text">
                <el-col :span="8">
                    <span class="content-text">平均切片大小:
                        {{ formatBytes1(biopsyHistory.averageFileSize) }}</span>
                </el-col>
                <el-col :span="8">
                    <span class="content-text">最大切片大小:
                        {{ formatBytes1(biopsyHistory.maxFileSize) }}</span>
                </el-col>
                <el-col :span="8">
                    <span class="content-text">最小切片大小：
                        {{ formatBytes1(biopsyHistory.minFileSize) }}</span>
                </el-col>
            </el-row>
            <el-row class="line-text">
                <el-col :span="8">
                    <span class="content-text">总上传时长:
                        {{ biopsyHistory.formatUploadCostTime }}</span>
                </el-col>
                <el-col :span="8">
                    <span class="content-text">平均上传时长:
                        {{ biopsyHistory.formatAverageUploadTime }}</span>
                </el-col>
            </el-row>
            <el-row class="line-text">
                <el-col :span="8">
                    <span class="content-text">上传开始: {{ biopsyHistory.uploadStartTime }}</span>
                </el-col>
                <el-col :span="8">
                    <span class="content-text">上传结束: {{ biopsyHistory.uploadEndTime }}</span>
                </el-col>
            </el-row>
            <!-- 新加扫描批次的详细列表 -->
            <el-table
                :data="pathologicalData"
                border
                :cell-style="{'text-align':'center'}"
                :header-cell-style="{
                'background-color': '#E6E9EF',
                'color':'#777C7C',
                'font-weight':'400',
                'font-size' : '15px',
                'border-right': '1px solid #ffffff',
                'text-align':'center'}"
                size="mini"
                style="width: 100%;margin-top: 20px;"
            >
                <el-table-column
                    prop="pathologyId"
                    label="病理编号"
                >
                </el-table-column>
                <el-table-column
                    prop="createTime"
                    label="扫描日期"
                >
                </el-table-column>
                <el-table-column
                    prop="progress"
                    label="扫描进度"
                >
                </el-table-column>
                <el-table-column
                    prop="originFilename"
                    label="源文件名"
                >
                </el-table-column>
                <el-table-column
                    prop="fileSizeStr"
                    label="切片大小"
                >
                </el-table-column>
                <el-table-column
                    prop="userName"
                    label="扫描员"
                >
                </el-table-column>

            </el-table>
            <el-row
                style="margin-top: 10px"
                align="right"
            >
                <el-pagination
                    @current-change="handleCurrentChange"
                    @size-change="handleSizeChange"
                    :current-page="1"
                    :page-size="15"
                    :page-sizes="pagination_page_sizes"
                    :total="dialogPageInfo.total"
                    style="text-align: center; margin-top: 12px;"
                    layout="sizes, prev, pager, next, total"
                >
                </el-pagination>
            </el-row>
            <span
                slot="footer"
                class="dialog-footer"
            >
                <el-button
                    @click="biopsyHistoryDialog.visible = false"
                    size="mini"
                >关闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import BaseTable from '@templates/components/BaseTable';
import { itemsPerPage } from '@/client/libs/util';
import { PAGINATION_PAGE_SIZES } from '@/client/consts/constant';

const echarts = require('echarts');

const BarsetOption = function (myChart) {
    this.optionDP = {
        color: ['#3398DB'],
        title: {
            text: '切片数量信息',
            left: '10%',
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                // 坐标轴指示器，坐标轴触发有效
                type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
            },
        },
        xAxis: [
            {
                type: 'category',
                data: [
                    '扫描总量',
                    '自动扫描',
                    '已匹配',
                    '未匹配',
                    '补传数量',
                    '诊断数量',
                ],
                axisTick: {
                    alignWithLabel: true,
                },
            },
        ],
        yAxis: [
            {
                type: 'value',
            },
        ],
        series: [
            {
                name: '数量',
                type: 'bar',
                barWidth: '60%',
                data: [
                    this.biopsyStatusData.scanCount,
                    this.biopsyStatusData.autoScanCount,
                    this.biopsyStatusData.matchedCount,
                    this.biopsyStatusData.unmatchCount,
                    this.biopsyStatusData.extraUploadCount,
                    this.biopsyStatusData.diagnosisCount,
                ],
            },
        ],
    };
    myChart.setOption(this.optionDP);
};

const LinesetOption = function (myChart) {
    this.optionDP = {
        title: {
            text: '切片存储趋势信息',
            left: '10%',
        },
        tooltip: {
            trigger: 'axis',
        },
        xAxis: [
            {
                type: 'category',
                data: this.biopsyStatusData.biopsyStorageDate,
            },
        ],
        yAxis: [
            {
                type: 'value',
                axisLabel: {
                    formatter: '{value} GB',
                },
            },
        ],
        series: [
            {
                name: '切片存储量',
                data: this.biopsyStatusData.biopsyStorage,
                type: 'line',
                barWidth: '60%',
                smooth: true,
            },
        ],
    };
    myChart.setOption(this.optionDP);
};

export default {
    name: 'DiagnosisScanStatistics',
    components: {
        BaseTable,
    },
    data() {
        return {
            pagination_page_sizes: PAGINATION_PAGE_SIZES,
            pathologicalData: [],
            dialogPageInfo: {
                page: 0,
                size: itemsPerPage.get(),
                total: 10,
            },
            inputBiopsyHistoryId: '',
            searchBiopsyHistoryId: '',
            activateName: 'overview',
            biopsyHistoryTable: {
                data: [],
                header: [
                    {
                        label: '扫描批次号',
                        prop: 'id',
                    },
                    {
                        label: '上传开始时间',
                        prop: 'uploadStartTime',
                    },
                    {
                        label: '上传结束时间',
                        prop: 'uploadEndTime',
                    },
                    {
                        label: '上传时长',
                        prop: 'formatUploadCostTime',
                    },
                    {
                        label: '扫描总数',
                        prop: 'scanFileCount',
                    },
                    {
                        label: '匹配总数',
                        prop: 'matchedCount',
                    },
                    {
                        label: '切片存储量',
                        prop: 'uploadedSize',
                    },
                    {
                        label: '扫描方式',
                        prop: 'isAddedBiopsy',
                    },
                ],
                operation: [
                    {
                        label: '详情',
                        functionKey: 'biopsyHistoryTableDetail',
                    },
                ],
                // 分页信息
                pageInfo: {
                    size: itemsPerPage.get(),
                    page: 1,
                    total: 0,
                },
            },

            biopsyHistoryDialog: {
                visible: false,
            },
            biopsyHistory: {
                id: 0,
                userName: '',
                userWorkNumber: '',

                scanFileCount: 0,
                autoMatchCount: 0,
                manualMatchCount: 0,

                averageFileSize: 0,
                maxFileSize: 0,
                minFileSize: 0,

                formatUploadCostTime: '',
                formatAverageUploadTime: '',

                uploadStartTime: '',
                uploadEndTime: '',

                status: '',
            },
            biopsyStatusData: {
                matchedRate: 0,
                averageBiopsy: 0, // [每一个诊断 匹配完成的切片数量/诊断数量]
                maxBiopsy: 0,
                minBiopsy: 0,
                biopsyStorageCount: 0,

                scanCount: 0,
                matchedCount: 0,
                unmatchCount: 0,
                autoScanCount: 0,
                extraUploadCount: 0,
                diagnosisCount: 0,

                biopsyStorageDate: [],
                biopsyStorage: [],
            },
        };
    },
    mounted() {
        this.biopsyHistoryTableRequest(); // 明细
        this.biopsyStatusObtain(this.formatDays.week, this.formatDays.now); // 概览
        this.BarsetOptionReset();
        this.LinesetOptionReset();
    },

    computed: {
        formatDays() {
            const dateArr = {};
            const nowDate = new Date();
            const oneWeekDate = new Date(nowDate - 7 * 24 * 3600 * 1000);
            dateArr.now = [
                nowDate.getFullYear(),
                nowDate.getMonth() + 1,
                nowDate.getDate(),
            ].join('-');
            dateArr.week = [
                oneWeekDate.getFullYear(),
                oneWeekDate.getMonth() + 1,
                oneWeekDate.getDate(),
            ].join('-');
            return dateArr;
        },
    },

    methods: {
        scanTableRequest(id) {
            this.$axios({
                method: 'GET',
                url: '/PROXY-Remote/biopsy/findBiopsyByHistoryId',
                params: {
                    biopsyHistoryid: id,
                    page: this.dialogPageInfo.page,
                    size: this.dialogPageInfo.size,
                },
            }).then((res) => {
                // 请求失败
                if (res.data.code !== 200) {
                    throw new Error(res.data);
                } else {
                    console.log('res.data', res.data);
                    this.pathologicalData = res.data.data;
                    this.pathologicalData.forEach((item) => {
                        item.userName = this.biopsyHistory.userName;
                        item.fileSizeStr = item.fileSizeStr + 'M';
                    });
                    this.dialogPageInfo = res.data.pageInfo;
                }
            });
        },
        //dialog的每批次扫描详情  分页处理开始
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.dialogPageInfo.pages = val - 1;
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            itemsPerPage.set(size);
            this.dialogPageInfo.sizes = val;
        },
        //dialog的每批次扫描详情  分页处理结束
        BarsetOptionReset() {
            const applicationBar = echarts.init(
                document.getElementById('consultationBar')
            );
            BarsetOption.call(this, applicationBar);
        },
        LinesetOptionReset() {
            const applicationLine = echarts.init(
                document.getElementById('consultationLine')
            );
            LinesetOption.call(this, applicationLine);
        },
        formatBytes(bytes, decimals = 1) {
            const Bytes = bytes * 1024 * 1024;
            if (Bytes === 0) return '0 Bytes';

            const k = 1024;
            const dm = decimals < 0 ? 0 : decimals;
            const sizes = [
                'Bytes',
                'KB',
                'MB',
                'GB',
                'TB',
                'PB',
                'EB',
                'ZB',
                'YB',
            ];

            const i = Math.floor(Math.log(Bytes) / Math.log(k));

            return `${parseFloat((Bytes / k ** i).toFixed(dm))} ${sizes[i]}`;
        },
        formatBytes1(Bytes, decimals = 1) {
            if (Bytes === 0 || !Bytes) {
                return '0 Bytes';
            }
            const k = 1024;
            const dm = decimals < 0 ? 0 : decimals;
            const sizes = [
                'Bytes',
                'KB',
                'MB',
                'GB',
                'TB',
                'PB',
                'EB',
                'ZB',
                'YB',
            ];

            const i = Math.floor(Math.log(Bytes) / Math.log(k));

            return `${parseFloat((Bytes / k ** i).toFixed(dm))} ${sizes[i]}`;
        },
        searchByBiopsyHistoryId() {
            this.searchBiopsyHistoryId = this.inputBiopsyHistoryId;
            this.biopsyHistoryTableRequest();
        },
        // 表格 - 按钮点击
        biopsyHistoryTableButtonClick(functionKey, row) {
            this[functionKey](row);
        },
        // 表格 - 详情
        biopsyHistoryTableDetail(row) {
            this.biopsyHistoryDialogOpen(row);
        },
        // 分页跳转
        biopsyHistoryTablePageJumpTo(val) {
            this.biopsyHistoryTable.pageInfo.page = val;
            this.biopsyHistoryTableRequest();
        },
        // 每页显示数量改变
        biopsyHistoryTableSizeChange(val) {
            itemsPerPage.set(val);
            this.biopsyHistoryTable.pageInfo.size = val;
            this.biopsyHistoryTableRequest();
        },
        // 请求切片数据
        async biopsyHistoryTableRequest() {
            try {
                await this.$axios({
                    method: 'GET',
                    url: '/PROXY-Remote/biopsy-history/page',
                    params: {
                        page: this.biopsyHistoryTable.pageInfo.page - 1,
                        size: this.biopsyHistoryTable.pageInfo.size,
                    },
                }).then((res) => {
                    // 请求失败
                    if (res.data.code !== 200) {
                        throw new Error(res.data);
                    }

                    // 请求成功
                    const result = res.data;
                    console.log('result', result);
                    // 分页信息
                    this.biopsyHistoryTable.pageInfo = {
                        total: result.pageInfo.total,
                        page: result.pageInfo.page + 1,
                        size: result.pageInfo.size,
                    };
                    // 查询结果数据
                    this.biopsyHistoryTable.data = [];
                    result.data.forEach((t, index) => {
                        const item = t;
                        item.index = index;
                        item.isAddedBiopsy =
                            item.isAddedBiopsy == 0
                                ? '自动'
                                : item.isAddedBiopsy == 1
                                ? '手动'
                                : '未知';
                        item.matchedCount =
                            item.autoMatchCount + item.manualMatchCount;
                        item.uploadedSize = this.formatBytes(
                            item.uploadedSize / 1024 / 1024
                        );
                        item.maxFileSize = this.formatBytes(
                            item.maxFileSize / 1024 / 1024
                        );
                        item.minFileSize = this.formatBytes(
                            item.minFileSize / 1024 / 1024
                        );
                        item.averageFileSize = this.formatBytes(
                            item.averageFileSize / 1024 / 1024
                        );

                        this.biopsyHistoryTable.data.push(item);
                    });
                });
            } catch (e) {
                // 跳出
            }
        },
        // 扫描详情
        async biopsyHistoryDialogOpen(row) {
            try {
                await this.$axios({
                    method: 'GET',
                    url: `/PROXY-Remote/biopsy-history/search/${row.id}`,
                }).then((res) => {
                    // 请求失败
                    if (res.data.code !== 200) {
                        throw new Error(res.data);
                    }
                    // 请求成功
                    const result = res.data;
                    // 查询结果数据
                    Object.keys(this.biopsyHistory).forEach((key) => {
                        this.biopsyHistory[key] = result.data[key];
                    });
                    console.log('this.biopsyHistory', this.biopsyHistory);
                    if (this.biopsyHistory.uploadEndTime == null) {
                        this.biopsyHistory.status = '正在扫描';
                    } else {
                        this.biopsyHistory.status = '扫描完成';
                    }
                    this.scanTableRequest(row.id);
                });
            } catch (e) {
                // 跳出
            }
            this.biopsyHistoryDialog.visible = true;
        },
        // 扫描统计
        async biopsyStatusObtain(start, end) {
            try {
                await this.$axios({
                    method: 'GET',
                    url: '/PROXY-Remote/scan-statistics',
                    params: {
                        startTime: start,
                        endTime: end,
                    },
                }).then((res) => {
                    if (res.data.code !== 200) {
                        throw new Error(res.data);
                    }
                    const result = res.data.data;
                    Object.keys(result).forEach((key) => {
                        if (result[key] instanceof Array) {
                            this.biopsyStatusData.biopsyStorageDate = [];
                            this.biopsyStatusData.biopsyStorage = [];
                            result[key].forEach((item) => {
                                this.biopsyStatusData.biopsyStorageDate.push(
                                    item.date
                                );
                                this.biopsyStatusData.biopsyStorage.push(
                                    (item.storage / 1024).toFixed(2)
                                );
                            });
                        }
                        this.biopsyStatusData[key] = result[key];
                    });
                    this.BarsetOptionReset();
                    this.LinesetOptionReset();
                });
            } catch (e) {
                throw new Error(e);
            }
        },
        // tab栏切换
        handleClick(tab, event) {
            console.log('tab栏切换', tab, event);
        },
    },
};
</script>

<style scoped>
.div-class {
    margin-top: 20px;
    text-align: center;
}

.data-table-style >>> .el-table__fixed-body-wrapper {
    top: 40px !important;
}
</style>
